package com.boe.hbd.client.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.boe.hbd.client.Constants;
import com.boe.hbd.client.R;
import com.boe.hbd.client.contextmenu.IconContextMenu.IconContextItemSelectedListener;
import com.boe.hbd.client.domain.MediaEntity; 
import com.boe.hbd.client.service.ImageLoaderService;
import com.boe.hbd.client.service.LandscapeService;
import com.boe.hbd.client.service.ServiceManager;

public class LandscapePhotosActivity extends Activity implements OnItemClickListener, IconContextItemSelectedListener, OnClickListener, TextWatcher { 
	private LandscapeService landscapeService;
	private Long landscapeId;
	private GridView photosGrid;
	private ImageView photoImageView;
	private ImageAdapter mAdapter;
	private List<MediaEntity> mediaEntities;
	private int origWidthOfImage = 0;
	private int origHeightOfImage= 0; 
	
	protected TextView mFilter = null ; 
	 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ServiceManager.getInstance(null).getService(ImageLoaderService.class);
		// STEP 1: initialize the landscapeId
		landscapeId = getIntent().getExtras().getLong(Constants.KEY_LANDSCAPE_ID);
		// STEP 2: load the grid item view to cache it
		setContentView(R.layout.landscape_photos_grid_item);
		photoImageView = (ImageView)findViewById(R.id.griditem_image);
		origWidthOfImage = photoImageView.getWidth();
		origHeightOfImage= photoImageView.getHeight();
		if (photoImageView.getLayoutParams() != null) {
			origWidthOfImage = photoImageView.getLayoutParams().width;
			origHeightOfImage= photoImageView.getLayoutParams().height;
		}
		// STEP 3: load the photos' grid view
		setContentView(R.layout.landscape_photos_activity);
		photosGrid = ((GridView) findViewById(R.id.photos));
		registerForContextMenu(photosGrid);
		photosGrid.setOnItemClickListener(this);
		findViewById(R.id.takephoto).setOnClickListener(this);
		findViewById(R.id.selectphoto).setOnClickListener(this);
		// STEP 4:  initialize the filter search box
        mFilter = (TextView) findViewById(R.id.searchFilter);
        if (mFilter != null) {
            mFilter.addTextChangedListener(this);
        } 
		// STEP 5: initialize services 
		landscapeService = ServiceManager.getInstance(null).getService(LandscapeService.class);  
		refreshGridView();
	}

	private void refreshGridView() {
	    if (landscapeId != null) {
			mediaEntities = landscapeService.findPhotosByFilterOfLandscape(landscapeId,mFilter.getText().toString());	
			mAdapter = new ImageAdapter(this,mediaEntities, R.layout.landscape_photos_grid_item, new String[] { "uri" }, new int[] { R.id.griditem_image});
			refreshGridViewLayout();
			photosGrid.setAdapter(mAdapter);
		}
    }
	
	public void onConfigurationChanged(Configuration newConfig){
		refreshGridViewLayout();
		super.onConfigurationChanged(newConfig);
	}
	
	private void refreshGridViewLayout() {
		int widthOfGrid  = getWindowManager().getDefaultDisplay().getWidth();
		int numColumns   = widthOfGrid/origWidthOfImage;	
		int newWidthOfImage = origWidthOfImage;
		int newHeightOfImage= origHeightOfImage; 
		if ( widthOfGrid % origWidthOfImage != 0 ) {
			numColumns = (int)Math.round((double)widthOfGrid / (double)origWidthOfImage );
			newWidthOfImage = (int)Math.round((double)widthOfGrid / numColumns) ;
			newHeightOfImage= newWidthOfImage * origHeightOfImage / origWidthOfImage;
		}
		if (mAdapter != null) {
			mAdapter.refreshLayoutParams(newWidthOfImage-1, newHeightOfImage-1);
		}
		photosGrid.setVerticalSpacing(1);
		photosGrid.setHorizontalSpacing(1);
		photosGrid.setColumnWidth(newWidthOfImage-1);
		photosGrid.setNumColumns(numColumns);
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		LandscapeHelper.buildContextMenu(this, this, position, R.menu.photos_of_landscape);
    }

	public void onIconContextItemSelected(MenuItem item, Object data) {
		if (data != null) {
			int position = (Integer)data;
			Long mediaId = mediaEntities.get(position).getId();
			if (item.getItemId() == R.id.deletePhoto ) {
				if (LandscapeHelper.removeEntity(this,mediaId)){
					refreshGridView();
				}
			} else if (item.getItemId() == R.id.showGallery ) {
				List<String> imgUrls = new ArrayList<String>(); 
				for (MediaEntity mediaEntity:mediaEntities) {
					if(mediaEntity.getUri() != null && mediaEntity.getUri().length() > Media.EXTERNAL_CONTENT_URI.toString().length() ) {
						String id = mediaEntity.getUri().substring(Media.EXTERNAL_CONTENT_URI.toString().length()+1);
						Cursor imgCursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[] { Media._ID , Media.DATA } , Media._ID + "=?" , new String[]{id}, null);
						if (imgCursor != null && imgCursor.moveToFirst()) {
							String imgUrl = "file://" + imgCursor.getString(imgCursor.getColumnIndexOrThrow(Media.DATA));
							imgUrls.add(imgUrl);
						}
					}
				}
				Intent intent = new Intent(this, ImagePagerActivity.class);
				intent.putExtra(Constants.IMAGES, imgUrls.toArray(new String[0]));
				intent.putExtra(Constants.IMAGE_POSITION, position);
				startActivity(intent);
			}  
		}
	}

	public void onClick(View v) { 
		LandscapeHelper.processRequestForLandscape(this, landscapeId, v.getId());
    }

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if ( LandscapeHelper.processResultForLandscape(this, requestCode, data, landscapeId)){
				refreshGridView();
			}
		}
	}

	public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) { 
	}

	public void afterTextChanged(Editable s) {
		refreshGridView();
	}
}